import Vue from "vue";
import VueRouter from "vue-router";
Vue.use(VueRouter);

/// 页面
import login from "../views/login";
import index from "../views/index";
import goods from "../views/goods";
import shopping_cart from "../views/shoppingCart";
import register from '../views/register'

//  路由列表
const routes = [
  {
    path: "/",
    name: "登录",
    meta: {
      title: "登录",
      needLogin: false,
    },
    component: login,
  },
  {
    path: "/login",
    name: "",
    meta: {
      title: "登录",
      needLogin: false,
    },
    component: login,
  },
  {
    path: "/register",
    name: "注册",
    meta: {
      title: "注册",
      needLogin: false,
    },
    component: register,
  },
  {
    path: "/index",
    name: "首页",
    meta: {
      title: "首页",
      needLogin: true,
    },
    component: index,
  },
  {
    path: "/goods",
    name: "商品",
    meta: {
      title: "商品",
      needLogin: true,
    },
    component: goods,
  },
  {
    path: "/shopping_cart",
    name: "购物车",
    meta: {
      title: "购物车",
      needLogin: true,
    },
    component: shopping_cart,
  },
  {
    path: "/401",
    meta: {
      title: "没有权限访问",
      needLogin: true,
    },
    component: () => import("@/views/errorPage/401.vue"),
  },
  ,
  {
    path: "*",
    meta: {
      title: "找不到该页面",
      needLogin: true,
    },
    component: () => import("@/views/errorPage/404.vue"),
  },
];

const router = new VueRouter({
  routes,
});

router.beforeEach((to, from, next) => {
  //  从 sessionStorage 中取出 isLogin 的值，如果没有则为默认为 false
  let isLogin = sessionStorage.getItem("isLogin") || false;
  // console.log(from);
  // console.log(to);

  // let from_fullPath = from.fullPath;
  // let to_fullPath = to.fullPath;

  let { title, needLogin } = to.meta;
  document.title = title;

  if (!isLogin && needLogin) {
    //  还未登录的状态或者进入需要登录的页面但是尚未登录
    next({
      path: "/login",
    });
  }
  // else if (from_fullPath === to_fullPath && from_fullPath === "/index") {

  // }
  else {
    next();
  }
  // next();
});

export default router;
